Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

Solution:

  1. public class Solution {
  2. public void merge(int[] nums1, int m, int[] nums2, int n) {
  3. int[] copy = new int[m];
  4. for (int k = 0; k < m; k++)
  5. copy[k] = nums1[k];
  6. int i = 0, j = 0;
  7. for (int k = 0; k < m + n; k++) {
  8. if (i >= m) nums1[k] = nums2[j++];
  9. else if (j >= n) nums1[k] = copy[i++];
  10. else if (copy[i] < nums2[j]) nums1[k] = copy[i++];
  11. else nums1[k] = nums2[j++];
  12. }
  13. }
  14. }